const { pool } = require('../config/db');

/**
 * 管理员操作日志中间件
 * 记录所有管理员的关键操作
 */
const adminLogger = (actionType, getDescription) => {
  return async (req, res, next) => {
    // 保存原始的res.json方法
    const originalJson = res.json.bind(res);

    // 重写res.json方法以捕获响应
    res.json = function(data) {
      // 调用原始方法发送响应
      originalJson(data);

      // 异步记录日志，不阻塞响应
      setTimeout(async () => {
        try {
          // 只记录成功的操作
          if (data.code === 200 || data.code === undefined) {
            const adminId = req.userId;
            const adminName = req.username || 'Unknown';
            
            // 获取操作描述
            let actionDesc = '';
            if (typeof getDescription === 'function') {
              actionDesc = getDescription(req, data);
            } else if (typeof getDescription === 'string') {
              actionDesc = getDescription;
            } else {
              actionDesc = `${actionType}操作`;
            }

            // 提取目标信息
            let targetType = null;
            let targetId = null;
            
            if (req.params.id) {
              targetId = req.params.id;
              // 根据路径推断目标类型
              const path = req.path;
              if (path.includes('book')) targetType = 'book';
              else if (path.includes('user')) targetType = 'user';
              else if (path.includes('borrow')) targetType = 'borrow';
              else if (path.includes('announcement')) targetType = 'announcement';
              else if (path.includes('reservation')) targetType = 'reservation';
            } else if (data.data && data.data.id) {
              targetId = data.data.id;
            }

            // 获取IP地址
            const ipAddress = req.ip || req.connection.remoteAddress || 'Unknown';
            const userAgent = req.get('User-Agent') || 'Unknown';

            // 记录日志
            await pool.query(`
              INSERT INTO admin_action_logs 
              (admin_id, admin_name, action_type, action_desc, 
               target_type, target_id, ip_address, user_agent,
               request_data, response_data, status)
              VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            `, [
              adminId,
              adminName,
              actionType,
              actionDesc,
              targetType,
              targetId,
              ipAddress,
              userAgent,
              JSON.stringify({
                method: req.method,
                path: req.path,
                body: req.body,
                query: req.query
              }),
              JSON.stringify(data),
              'success'
            ]);
          }
        } catch (err) {
          console.error('记录管理员操作日志失败:', err);
        }
      }, 0);
    };

    next();
  };
};

/**
 * 简化的日志记录函数
 */
const logAdminAction = async (adminId, adminName, actionType, actionDesc, targetType = null, targetId = null) => {
  try {
    await pool.query(`
      INSERT INTO admin_action_logs 
      (admin_id, admin_name, action_type, action_desc, target_type, target_id, status)
      VALUES (?, ?, ?, ?, ?, ?, 'success')
    `, [adminId, adminName, actionType, actionDesc, targetType, targetId]);
    return true;
  } catch (err) {
    console.error('记录管理员操作日志失败:', err);
    return false;
  }
};

/**
 * 查询管理员操作日志
 */
const getAdminLogs = async (req, res, next) => {
  try {
    const { page = 1, limit = 20, adminId, actionType, targetType, startDate, endDate } = req.query;
    const offset = (page - 1) * limit;

    let whereClause = 'WHERE 1=1';
    let params = [];

    if (adminId) {
      whereClause += ' AND admin_id = ?';
      params.push(adminId);
    }

    if (actionType) {
      whereClause += ' AND action_type = ?';
      params.push(actionType);
    }

    if (targetType) {
      whereClause += ' AND target_type = ?';
      params.push(targetType);
    }

    if (startDate) {
      whereClause += ' AND create_time >= ?';
      params.push(startDate);
    }

    if (endDate) {
      whereClause += ' AND create_time <= ?';
      params.push(endDate);
    }

    const [logs] = await pool.query(`
      SELECT
        id,
        admin_id,
        admin_name,
        action_type,
        action_desc,
        target_type,
        target_id,
        ip_address,
        status,
        create_time
      FROM admin_action_logs
      ${whereClause}
      ORDER BY create_time DESC
      LIMIT ? OFFSET ?
    `, [...params, parseInt(limit), offset]);

    const [total] = await pool.query(`
      SELECT COUNT(*) as count FROM admin_action_logs ${whereClause}
    `, params);

    res.json({
      code: 200,
      data: {
        logs,
        pagination: {
          current: parseInt(page),
          limit: parseInt(limit),
          total: total[0].count,
          pages: Math.ceil(total[0].count / limit)
        }
      },
      message: '获取成功'
    });
  } catch (err) {
    next(err);
  }
};

/**
 * 获取日志详情
 */
const getLogDetail = async (req, res, next) => {
  try {
    const { id } = req.params;

    const [logs] = await pool.query(
      'SELECT * FROM admin_action_logs WHERE id = ?',
      [id]
    );

    if (logs.length === 0) {
      return res.json({
        code: 404,
        message: '日志不存在'
      });
    }

    res.json({
      code: 200,
      data: logs[0],
      message: '获取成功'
    });
  } catch (err) {
    next(err);
  }
};

/**
 * 获取操作统计
 */
const getLogStats = async (req, res, next) => {
  try {
    const { days = 7 } = req.query;

    const [stats] = await pool.query(`
      SELECT
        COUNT(*) as total_actions,
        COUNT(DISTINCT admin_id) as active_admins,
        COUNT(DISTINCT DATE(create_time)) as active_days,
        action_type,
        COUNT(*) as action_count
      FROM admin_action_logs
      WHERE create_time >= DATE_SUB(NOW(), INTERVAL ? DAY)
      GROUP BY action_type
      ORDER BY action_count DESC
    `, [parseInt(days)]);

    res.json({
      code: 200,
      data: stats,
      message: '获取成功'
    });
  } catch (err) {
    next(err);
  }
};

module.exports = {
  adminLogger,
  logAdminAction,
  getAdminLogs,
  getLogDetail,
  getLogStats
};

